//
//  PHPhotoLibraryTool.swift
//  Phone
//
//  Created by redjun Z on 2019/1/31.
//  Copyright © 2019 network.xiaozhang.com. All rights reserved.
//

import Foundation
import UIKit
//import ALAssetsLibrary
import Photos

func srh_saveImage(image: UIImage,completionHandle:@escaping (_ error: Error?,_ str: String?)->Void) {
    let library = PHPhotoLibrary.shared()
    var localIdentifier = ""
    library.performChanges({
        // 2.1 创建一个相册变动请求
        let collectionRequest = getCurrentPhotoCollectionWithAlbumName(albumName: "SRHAlbumName")
        // 2.2 根据传入的照片，创建照片变动请求
        let assetRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
        // 2.3 创建一个占位对象
        let placeholder = assetRequest.placeholderForCreatedAsset
        localIdentifier = placeholder?.localIdentifier ?? "zhj"
        
         // 2.4 将占位对象添加到相册请求中
        collectionRequest.addAssets([placeholder] as NSFastEnumeration)
    }) { (success, error) in
        if (error != nil) {
            completionHandle(error, "保存失败")
        } else {
            completionHandle(error, localIdentifier)
        }
    }
}

//PHAssetCollectionChangeRequest
func getCurrentPhotoCollectionWithAlbumName(albumName: String) -> PHAssetCollectionChangeRequest {
//    1.创建搜集合
    let result: PHFetchResult = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.album, subtype: PHAssetCollectionSubtype.albumRegular, options: nil)
    // 2. 遍历搜索集合并取出对应的相册，返回当前的相册changeRequest
    for index in 0..<result.count {
        let assetCollection: PHAssetCollection = result[index]
        if (assetCollection.localizedTitle?.contains(albumName))! {
            let collectionRuquest = PHAssetCollectionChangeRequest.init(for: assetCollection)
            return collectionRuquest!
        }
    }
     // 3. 如果不存在，创建一个名字为albumName的相册changeRequest
    let collectionRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: albumName)
    return collectionRequest
}



